package org.blog.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class ObjectToMap {

    public static Map<String, Object> convertBeanToMap(Object obj) throws InvocationTargetException, IllegalAccessException {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            boolean accessFlag = fields[i].isAccessible();
            fields[i].setAccessible(true);
            Object o = fields[i].get(obj);
            if (o != null) {
                map.put(varName, o);
            }
            fields[i].setAccessible(accessFlag);
        }

        return map;
    }
}
